package 力扣_树算法.路径;


import java.util.*;

/**257. 二叉树的所有路径
 * @author zx
 * @create 2022-04-11 20:58
 */
public class Num257 {
    List<String> res = new ArrayList<>();
    public List<String> binaryTreePaths(TreeNode root) {
        helper(root,"");
        return res;
    }
    private void helper(TreeNode root, String path){
        if(root == null){
            return;
        }
        if(root.left == null && root.right == null){
            res.add(path + root.val);
        }
        helper(root.left, path + root.val + "->");
        helper(root.right, path + root.val + "->");
    }







    /**
     * @return 迭代
     */
    public List<String> binaryTreePaths3(TreeNode root) {
        List<String> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        Deque<TreeNode> nodeQueue = new ArrayDeque<>();
        Deque<String> pathQueue = new ArrayDeque<>();
        nodeQueue.offer(root);
        // pathQueue.offer(new String("" + root.val));
        pathQueue.offer(Integer.toString(root.val));

        while(!nodeQueue.isEmpty()){
            TreeNode node = nodeQueue.poll();
            String path = pathQueue.poll();
            if(node.left == null && node.right == null){
                res.add(path);
            }else{
                if(node.left != null){
                    nodeQueue.offer(node.left);
                    pathQueue.offer(new StringBuffer(path).append("->").append(node.left.val).toString());
                }
                if(node.right != null){
                    nodeQueue.offer(node.right);
                    pathQueue.offer(new StringBuffer(path).append("->").append(node.right.val).toString());
                }
            }
        }
        return res;
    }
}
class TreeNode {
    public int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}